<?
class XMLLib
{
	static function _xml_encode_attribute( $t )
	{
		$t = preg_replace("/&(?!#[0-9]+;)/s", '&amp;', $t );
		$t = str_replace( "<", "&lt;"  , $t );
		$t = str_replace( ">", "&gt;"  , $t );
		$t = str_replace( '"', "&quot;", $t );
		$t = str_replace( "'", '&#039;', $t );
		
		return $t;
	}
	
	/*-------------------------------------------------------------------------*/
	// INTERNAL: Encodes an attribute string
	/*-------------------------------------------------------------------------*/
	
	static function _xml_decode_attribute( $t )
	{
		$t = str_replace( "&amp;" , "&", $t );
		$t = str_replace( "&lt;"  , "<", $t );
		$t = str_replace( "&gt;"  , ">", $t );
		$t = str_replace( "&quot;", '"', $t );
		$t = str_replace( "&#039;", "'", $t );
		
		return $t;
	}
	
	/*-------------------------------------------------------------------------*/
	// INTERNAL: Encodes a string to make it safe (uses cdata)
	/*-------------------------------------------------------------------------*/
	
	static function _xml_encode_string( $v )
	{
		if ( preg_match( "/['\"\[\]<>&]/", $v ) )
		{
			$v = "<![CDATA[" . $this->_xml_convert_safecdata($v) . "]]>";
		}
		
		if ( $this->collapse_newlines )
		{
			$v = str_replace( "\r\n", "\n", $v );
		}
		
		return $v;
	}
	
	/*-------------------------------------------------------------------------*/
	// INTERNAL: Ensures no embedding of cdata
	/*-------------------------------------------------------------------------*/
	
	static function _xml_convert_safecdata( $v )
	{
		$v = str_replace( "<![CDATA[", "<!�|CDATA|", $v );
		$v = str_replace( "]]>"      , "|�]>"      , $v );
		return $v;
	}
	
	/*-------------------------------------------------------------------------*/
	// INTERNAL: Uncoverts safe embedding
	/*-------------------------------------------------------------------------*/
	
	static function _xml_unconvert_safecdata( $v )
	{
		$v = str_replace( "<!�|CDATA|", "<![CDATA[", $v );
		$v = str_replace( "|�]>"      , "]]>"      , $v );
		return $v;
	}
	
    static function xml2assoc(&$xml) {
        $assoc = NULL;
        $n = 0;
        while ($xml->read()) {
            if ($xml->nodeType == XMLReader::END_ELEMENT)
                break;
            if ($xml->nodeType == XMLReader::ELEMENT and !$xml->isEmptyElement) {
                if ($xml->depth == 2) {
                    $assoc[$xml->name] = ECLib::xml2assoc($xml);
                } else {
                    $assoc[$n][$xml->name] = ECLib::xml2assoc($xml);
                }
                $n++;
            } else if ($xml->isEmptyElement) {
                $assoc[$n][$xml->name] = "";
                $n++;
            } else if ($xml->nodeType == XMLReader::TEXT) {
                $assoc = $xml->value;
            }
        }
        return $assoc;
    }
}
?>